/*************************************************************************
*																		 *
*				code by Miles Chen (v-mich) 2007.10.13					 *
*																		 *
*																		 *
*************************************************************************/

#pragma once

#include "commdef-int.h"

namespace System{namespace Windows{namespace Forms{
	namespace UIAutomation{

#define SHORT_TIME 200
#define TRY_MAX_TIMES 50

		BOOL CALLBACK EnumThreadWindowProc(HWND hWnd, LPARAM lParam)
		{
			*(HWND*)lParam = hWnd;
			return FALSE;
		}

		BOOL GetProcessMainWindowHandle(LPPROCESS_INFORMATION ppi, LPCWSTR lpszClass, LPCWSTR lpszCaption, OUT HWND* handle)
		{
			int tryTime = 0;
			WCHAR szClass[MAX_CHAR];
			WCHAR szCaption[MAX_CHAR];
			while(TRUE)
			{
				Sleep( SHORT_TIME );
				EnumThreadWindows(ppi->dwThreadId, (WNDENUMPROC)&EnumThreadWindowProc, (LPARAM)handle);
				if( tryTime++ == TRY_MAX_TIMES )
				{
					return FALSE;
				}
				else
				{
					if(*handle)
					{
						if(!lpszClass && !lpszCaption)
							break;
						else if(lpszClass && lpszCaption)
						{
							GetWindowTextW(*handle, szCaption, MAX_CHAR);
							GetClassNameW(*handle, szClass, MAX_CHAR);

							if(System::String::Compare(szCaption, lpszCaption) == 0
								&& System::String::Compare(szClass, lpszClass) == 0)
								break;
						}
						else if(lpszClass)
						{
							GetClassNameW(*handle, szClass, MAX_CHAR);

							if(System::String::Compare(szClass, lpszClass) == 0)
								break;
						}
						else if(lpszCaption)
						{
							GetWindowTextW(*handle, szCaption, MAX_CHAR);

							if(System::String::Compare(szCaption, lpszCaption) == 0)
								break;
						}
					}
				}
			}

			return TRUE;
		}

		BOOL GetFirstChildHandle(HWND hwndParent, OUT HWND* handle)
		{
			int tryTime = 0;
			do
			{
				Sleep( SHORT_TIME );
				*handle = FindWindowExW(hwndParent, NULL, NULL, NULL);
				if( tryTime++ == TRY_MAX_TIMES )
				{
					return FALSE;
				}
			}while(!*handle);

			return TRUE;
		}

		BOOL GetChildHandle(HWND hwndParent, int nIDDlgItem, OUT HWND* handle)
		{
			int tryTime = 0;
			do
			{
				Sleep( SHORT_TIME );
				*handle = GetDlgItem(hwndParent, nIDDlgItem);
				if( tryTime++ == TRY_MAX_TIMES )
				{
					return FALSE;
				}
			}while(!*handle);

			return TRUE;
		}

		BOOL WaitForEnable(HWND hWnd)
		{
			int tryTime = 0;
			do
			{
				Sleep( SHORT_TIME );
				if( tryTime++ == TRY_MAX_TIMES )
				{
					return FALSE;
				}
			}while(GetWindowLongW(hWnd, GWL_STYLE) & WS_DISABLED);

			return TRUE;
		}

	}}}}


